import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../bean/BookStyle.dart';
import '../../bean/read_theme.dart';
import '../../config/shared_preference_provider.dart';
import '../js/convert_dart_color_to_js.dart';

Future<void> webviewInitialVariable(
    InAppWebViewController controller,
    String url,
    String cfi, {
      BookStyle? bookStyle,
      int? textIndent,
      String? textColor,
      String? fontName,
      String? fontPath,
      String? backgroundColor,
      bool? importing,
    }) async {
  ReadTheme readTheme = Prefs().readTheme;
  bookStyle ??= Prefs().bookStyle;
  textColor ??= readTheme.textColor;
  fontName ??= Prefs().font.name;
  fontPath ??= Prefs().font.path;
  backgroundColor ??= readTheme.backgroundColor;
  importing ??= false;

  textColor = convertDartColorToJs(textColor);
  backgroundColor = convertDartColorToJs(backgroundColor);

  const minWebviewVersion = 92;

  String replaceSingleQuote(String value) {
    return value.replaceAll("'", "\\'");
  }

  // 先检查WebView环境
  controller.evaluateJavascript(source: '''
    console.log('navigator.userAgent', navigator.userAgent)
  ''');

  // 初始化必要的全局变量
  await controller.evaluateJavascript(source: '''
    window.url = '$url';
    window.initialCfi = '$cfi';
    window.style = {
      fontSize: ${bookStyle.fontSize},
      fontName: '$fontName',
      fontPath: '$fontPath',
      fontWeight: ${bookStyle.fontWeight},
      letterSpacing: ${bookStyle.letterSpacing},
      spacing: ${bookStyle.lineHeight},
      paragraphSpacing: ${bookStyle.paragraphSpacing},
      textIndent: ${bookStyle.indent},
      fontColor: '$textColor',
      backgroundColor: '$backgroundColor',
      topMargin: ${bookStyle.topMargin},
      bottomMargin: ${bookStyle.bottomMargin},
      sideMargin: ${bookStyle.sideMargin},
      justify: true,
      hyphenate: true,
      pageTurnStyle: 'slide',
      maxColumnCount: ${bookStyle.maxColumnCount},
    };
    window.importing = $importing;
    console.log('初始化变量完成', { url, initialCfi, style });
  ''');


  final script = '''
      const webviewVersion = navigator.userAgent.match(/Chrome\\/(\\d+)/)?.[1]
      const appleWebkitVersion = navigator.userAgent.match(/AppleWebKit\\/(\\d+)/)?.[1]
      const isApple = navigator.userAgent.includes('Macintosh') || navigator.userAgent.includes('iPhone') || navigator.userAgent.includes('iPad')
      if (
          (!isApple && (webviewVersion && webviewVersion < $minWebviewVersion || !webviewVersion))
          || (isApple && (appleWebkitVersion && appleWebkitVersion < 605 ))
      ) {
        window.flutter_inappwebview.callHandler('webviewVersion', webviewVersion)
      }
      const importing = $importing
      const url = '${replaceSingleQuote(url)}'
      let initialCfi = '${replaceSingleQuote(cfi)}'
      let style = {
          fontSize: ${bookStyle.fontSize},
          fontName: '${replaceSingleQuote(fontName)}',
          fontPath: '${replaceSingleQuote(fontPath)}',
          fontWeight: ${bookStyle.fontWeight},
          letterSpacing: ${bookStyle.letterSpacing},
          spacing: ${bookStyle.lineHeight},
          paragraphSpacing: ${bookStyle.paragraphSpacing},
          textIndent: ${bookStyle.indent},
          fontColor: '#$textColor',
          backgroundColor: '#$backgroundColor',
          topMargin: ${bookStyle.topMargin},
          bottomMargin: ${bookStyle.bottomMargin},
          sideMargin: ${bookStyle.sideMargin},
          justify: true,
          hyphenate: true,
          pageTurnStyle: '${Prefs().pageTurnStyle.name}',
          maxColumnCount: ${bookStyle.maxColumnCount},
      }
      let readingRules = {
        convertChineseMode: '${Prefs().readingRules.convertChineseMode.name}',
        bionicReadingMode: ${Prefs().readingRules.bionicReading},
      }

      window.loadBook()
  ''';
  // controller.addJavaScriptHandler(
  //     handlerName: 'webviewInitialVariable',
  //     callback: (args) async {
  await controller.evaluateJavascript(source: script);
  //   return null;
  // });
  controller.addJavaScriptHandler(
      handlerName: 'webviewVersion',
      callback: (args) async {
        SmartDialog.show(
          animationType: SmartAnimationType.fade,
          builder: (context) {
            final version = args[0];
            return AlertDialog(
              title: const Center(
                child: Icon(Icons.warning_rounded),
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("L10n",
                      style: Theme
                          .of(context)
                          .textTheme
                          .titleMedium),
                  Text("$version"),
                ],
              ),
              actions: [
                TextButton(
                    onPressed: () {
                      SmartDialog.dismiss();
                    },
                    child: Text("取消")),
                TextButton(
                    onPressed: () {
                      SmartDialog.dismiss();
                    },
                    child: Text("更新"))
              ],
            );
          },
        );
        return null;
      });
}
